package com.ukefu.webim.service.task;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;

import com.ukefu.core.UKDataContext;
import com.ukefu.webim.service.repository.SystemUpdateconRepository;
import com.ukefu.webim.web.model.NoticeMsg;
import com.ukefu.webim.web.model.SystemUpdatecon;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class DownLoadFileTask implements Runnable{
	
	private String urlStr ;
	private String fileName ;
	private String savePath ;
	private String systemUpdateconId;
	private String type;
	private  SystemUpdateconRepository systemUpdateconRes ;
	
	public DownLoadFileTask(String systemUpdateconId,String urlStr , String fileName , String savePath,String type) {
		this.urlStr = urlStr;
		this.fileName = fileName;
		this.savePath = savePath;
		this.systemUpdateconId = systemUpdateconId;
		this.type = type;
		this.systemUpdateconRes = UKDataContext.getContext().getBean(SystemUpdateconRepository.class);
	}

	
	
	@Override
	public void run() {
		try {
			downLoadFromUrl(urlStr, fileName, savePath);
			if(StringUtils.isNotBlank(this.systemUpdateconId)) {
				SystemUpdatecon systemUpdatecon = this.systemUpdateconRes.findByIdAndOrgi(this.systemUpdateconId,UKDataContext.SYSTEM_ORGI.toString());
				if(StringUtils.isNotBlank(type)) {
					if("sql".equals(type)) {
						systemUpdatecon.setSqlurldownload("2");
						this.systemUpdateconRes.save(systemUpdatecon);
					}else if("jar".equals(type)) {
						systemUpdatecon.setJarurldownload("2");
						this.systemUpdateconRes.save(systemUpdatecon);
					}else if("rollbacksql".equals(type)) {
						systemUpdatecon.setRollbacksqlurldownload("2");
						this.systemUpdateconRes.save(systemUpdatecon);
					}
				}
			}
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从输入流中获取字节数组
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
		byte[] buffer = new byte[1024];  
		int len = 0;  
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		while((len = inputStream.read(buffer)) != -1) {  
			bos.write(buffer, 0, len);  
		}  
		bos.close();  
		return bos.toByteArray();  
	}  
	
	/**
	 * 从网络Url中下载文件
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{

		PoolingHttpClientConnectionManager connMgr;
		RequestConfig requestConfig;
		final int MAX_TIMEOUT = 300000;
		// 设置连接池
		connMgr = new PoolingHttpClientConnectionManager();
		// 设置连接池大小
		connMgr.setMaxTotal(100);
		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();

		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpPost = new HttpGet(urlStr);
			httpPost.setConfig(requestConfig);
			HttpResponse httpRes = httpclient.execute(httpPost);

			HttpEntity entity = httpRes.getEntity();
			if (entity != null) {
				InputStream result = entity.getContent();

				File saveDir = new File(savePath);
				if(!saveDir.exists()){
					saveDir.mkdir();
				}
				System.out.println(saveDir+File.separator+fileName);
				File file = new File(saveDir+File.separator+fileName);
				FileOutputStream fos = new FileOutputStream(file);

				try{
					byte[] data = new byte[1024 * 1024];
					int len = 0;
					while((len = result.read(data) ) != -1){
						fos.write(data , 0 , len);
						fos.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					if(fos != null){
						try {
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(httpclient!=null) {
				httpclient.close();
			}
		}

		//URL url = new URL(urlStr);
		/*URLConnection conn = url.openConnection();
                //设置超时间为6秒
		conn.setConnectTimeout(15*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
 
		//得到输入流
		InputStream inputStream = conn.getInputStream();
		//获取自己数组
		byte[] getData = readInputStream(inputStream);
 
		//文件保存位置
		File saveDir = new File(savePath);
		if(!saveDir.exists()){
			saveDir.mkdir();
		}
		File file = new File(saveDir+File.separator+fileName);    
		FileOutputStream fos = new FileOutputStream(file);     
		fos.write(getData); 
		if(fos!=null){
			fos.close();  
		}
		if(inputStream!=null){
			inputStream.close();
		}*/
		System.out.println("info:"+urlStr+" download success");
 
	}

}
